<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/resources/upload/lib/crypto1/crypto/crypto.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/resources/upload/lib/crypto1/hmac/hmac.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/resources/upload/lib/crypto1/sha1/sha1.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/resources/upload/lib/base64.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/resources/upload/lib/plupload-2.1.2/js/plupload.full.min.js"></script>
</head>
<style type="text/css">
.progress {
	width: 100%;
	position: fixed;
	top: -6px;
	left: 0px;
	height: 2px;
	background-color: #c7c7c7;
}

#selectfiles {
	color: white;
	background-color: #007aff;
	border-radius: 3px;
	width: 95px;
	height: 35px;
	text-align: center;
	display: block;
	margin: auto;
	margin-top: 2px;
	z-index: 0 !important;
}
</style>
<form class="mui-input-group">
	<div class="mui-input-row">
		<label>资源名称:</label> <input type="text" class="name" name="name"
			placeholder="请输入资源名称"> <input type="hidden" id="url"
			name="url"> <span class="must">*</span>
	</div>

	<div id="ossfile"></div>

	<div class="mui-input-row">
		<label>文件上传:</label>
		<div id="container">
			<a id="selectfiles" style="line-height: 40px;"
				href="javascript:void(0);">上传文件</a>
		</div>
	</div>
	<div class="mui-input-row">
		<label>描述:</label> <input type="text" class="des" name="des"
			placeholder="请输入位置等描述">
	</div>
	<div class="mui-input-row">
		<label>选择类型:</label> <select class="type" name="type">
			<option value="0" selected="selected">图片</option>
			<option value="1">视频</option>
			<option value="2">音频</option>
		</select>
	</div>
	<div class="mui-input-row">
		<label>选择公司:</label> <select class="adUrl" name="compId">
			<c:forEach items="${compList }" var="list">
				<option value="${list.compId }">${list.compName }</option>
			</c:forEach>
		</select>
	</div>
	<div class="mui-button-row">
		<a type="button" class="mui-btn mui-btn-primary submit">提交</a>
	</div>
</form>
<script type="text/javascript">
    	mui('#offCanvasContentScroll').scroll().scrollTo(0,0);
    	
    	$(".mui-title").html("添加广告资源");
    	
		var key;
		var flag=1;
	
		accessid= 'LTAIuTQ4eUb4Unt1';
		accesskey= 'Yo7NQiAb9MCObQTMqGA6UcOoGWWaIS';
		host = 'http://hengzhu-storage-1.oss-cn-hangzhou.aliyuncs.com';
	
		g_dirname = ''
		g_object_name = ''
		g_object_name_type = 'random_name'
		now = timestamp = Date.parse(new Date()) / 1000; 
	
		var policyText = {
		    "expiration": "2080-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
		    "conditions": [
		    ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
		    ]
		};
	
		var policyBase64 = Base64.encode(JSON.stringify(policyText))
		message = policyBase64
		var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
		var signature = Crypto.util.bytesToBase64(bytes);
	
		function random_string(len) {
		　　len = len || 32;
		　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
		　　var maxPos = chars.length;
		　　var pwd = '';
		　　for (i = 0; i < len; i++) {
		    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		    }
		    return pwd;
		}
	
		function get_suffix(filename) {
		    pos = filename.lastIndexOf('.')
		    suffix = ''
		    if (pos != -1) {
		        suffix = filename.substring(pos)
		    }
		    return suffix;
		}
	
		function calculate_object_name(filename)
		{
		    if (g_object_name_type == 'local_name')
		    {
		        g_object_name += "${filename}"
		    }
		    else if (g_object_name_type == 'random_name')
		    {
		        suffix = get_suffix(filename)
		        g_object_name = g_dirname + random_string(10) + suffix
		    }
		    return ''
		}
	
		function get_uploaded_object_name(filename)
		{
		    if (g_object_name_type == 'local_name')
		    {
		        tmp_name = g_object_name
		        tmp_name = tmp_name.replace("${filename}", filename);
		        return tmp_name
		    }
		    else if(g_object_name_type == 'random_name')
		    {
		        return g_object_name
		    }
		}
	
		function set_upload_param(up, filename, ret)
		{
		    g_object_name = g_dirname;
		    if (filename != '') {
		        suffix = get_suffix(filename)
		        calculate_object_name(filename)
		    }
		    new_multipart_params = {
		        'key' : g_object_name,
		        'policy': policyBase64,
		        'OSSAccessKeyId': accessid, 
		        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
		        'signature': signature,
		    };
	
		    up.setOption({
		        'url': host,
		        'multipart_params': new_multipart_params
		    });
	
		    up.start();
		}
	
		var uploader = new plupload.Uploader({
			runtimes : 'html5,flash,silverlight,html4',
			browse_button : 'selectfiles', 
		    //multi_selection: false,
			container: document.getElementById('container'),
			flash_swf_url : '${pageContext.request.contextPath}/resources/upload/lib/plupload-2.1.2/js/Moxie.swf',
			silverlight_xap_url : '${pageContext.request.contextPath}/resources/upload/lib/plupload-2.1.2/js/Moxie.xap',
		    url : 'http://oss.aliyuncs.com',
	
			init: {
				PostInit: function() {
					document.getElementById('ossfile').innerHTML = '';
				},
	
				FilesAdded: function(up, files) {
					plupload.each(files, function(file) {
						document.getElementById('ossfile').innerHTML = '<div id="' + file.id + '" style="position: absolute;right: 30px;top: 50px;"><b></b>'
						+'<div class="progress"><div class="progress-bar" style="width: 0%;height:2px;background-color: #0085ff;"></div></div>'
						+'</div>';
					});
				 	set_upload_param(uploader, '', false);
				},
	
				BeforeUpload: function(up, file) {
		            set_upload_param(up, file.name, true);
		        },

				UploadProgress: function(up, file) {
					var d = document.getElementById(file.id);
					d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
		            var prog = d.getElementsByTagName('div')[0];
					var progBar = prog.getElementsByTagName('div')[0]
					progBar.style.width= file.percent+'%';
					progBar.setAttribute('aria-valuenow', file.percent);
					$("#selectfiles").html("上传中..");
					/* $("#selectfiles").css({"animation":""}); */
					if(file.percent == 100){
					/* 	$("#ossfile b").css({"display":"block","animation":"progress-done-pre 2s ease-out forwards"});
						$("#selectfiles").css({"animation":"progress-font-done 2s ease-out"}); */
						$("#selectfiles").html("上传完成");
					}
				},
	
				FileUploaded: function(up, file, info) {
		            if (info.status == 200)
		            {
		            	key = get_uploaded_object_name(file.name);
		            	var arr = key.split("/");
		            	
		            	key = arr[arr.length-1];
		            	document.getElementById("url").value = key;
		            }
		            else
		            {
		            	flag=3;
		            } 
				},
	
				Error: function(up, err) {
					flag=3;
				}
			}
		});
	
		uploader.init();
		
	/* ---------------------------广告 ---------------------------- */
	   
	$(".submit").on("touchstart",function(){
		   var param = $("form").serialize();
	    	let name = $(".name").val();
	    	let url = $("#url").val();

	    	if(name == ""){
	    		mui.toast("带 "+'<span style="color:red;">*</span> 为必填项');
	    	}else if(url == ""){
	    		mui.toast("未完成上传");
	    	}else if(flag == 3){
	    		mui.toast("上传失败");
	    	}else{
				$.post("/publishFile/addFile",param,function(res){
					if(res.success){
						mui.toast("添加成功");
						history.back();
			    	}else{
			    		mui.toast(res.message);
			    	}
					
				})
	    	}
	   })
	   
	</script>
</html>